<?php

namespace App\Http\Controllers\TK_Api;

use App\Http\Requests\TK\UserLoginRequest;
use App\Models\User;
use App\Service\Jwt\TokenService;
use App\Service\Wechat\WechatAppService;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\JsonResponse;

class AuthController extends ApiBaseController
{
    /**
     * 登录
     * @param UserLoginRequest $request
     * @param WechatAppService $wechatAppService
     * @param TokenService $tokenService
     * @return JsonResponse|object
     * @throws Exception
     */
    public function login(UserLoginRequest $request, WechatAppService $wechatAppService, TokenService $tokenService) {
        $params = $request->validated();

        // 登录逻辑处理
        $wxCode = $params['code'];
        $wechatResult = $wechatAppService->getOpenID($wxCode);
        $user = User::where('wxOpenid', $wechatResult['openid'])->first();

        // 没有找到用户
        if (!$user) {
            $user = User::create([
                'wxOpenid' => $wechatResult['openid'],
                'status' => 'normal',
                'province' => '河北省',
                'avatar' => 'https://files.qihangzhukao.com/morentouxiang.png',
                // 'avatar' => '',
                'createtime' => time()
            ]);
            $newUser = true;
        }else {
            if (empty($user->avatar)) $user->avatar = 'https://files.qihangzhukao.com/morentouxiang.png';
            $user->save();
            $newUser = !$user->nickname || !$user->avatar;
        }

        if ($user->status != 'normal') {
            throw new Exception('防盗刷机制，请联系客服！');
        }

        // 签发token
        $token = $tokenService->createToken($user);
        $data['token'] = $token;
        $data['expires'] = Carbon::now()->addHours(120)->timestamp;
        $data['userInfo'] = [
            'id' => $user->id,
            'username' => $user->username ?? $user->nickname,
            'nickname' => $user->nickname,
            'mobile' => $user->mobile,
            'avatar' => $user->avatar,
            // 'avatar' => '',
            'gender' => $user->gender,
            'province' => $user->province,
            'ksCountdown' => $user->ksCountdown ?? null,
            'ksCountdownDays' => $user->ksCountdown ? Carbon::now()->diffInDays(Carbon::make($user->ksCountdown)) : null,
            'ksDaysCount' => $user->ksDaysCount ?? 0
        ];
        $data['haveInfo'] = !$newUser;

        return $this->restful($data);
    }
}
